// funi-interactions.js
(function () {
  const SIDEBAR_COLLAPSED_KEY = 'funi-sidebar-collapsed';
  const MENU_GROUP_COLLAPSED_PREFIX = 'funi-menu-group-collapsed-';

  function toggleSidebar() {
    const sidebar = document.getElementById('sidebar');
    if (sidebar) {
      sidebar.classList.toggle('collapsed');
      const isCollapsed = sidebar.classList.contains('collapsed');
      localStorage.setItem(SIDEBAR_COLLAPSED_KEY, isCollapsed);
      adjustMenuTextVisibility(isCollapsed);
    }
  }

  function adjustMenuTextVisibility(isCollapsed) {
    const menuTexts = document.querySelectorAll('.funi-menu-text');
    menuTexts.forEach(text => {
      text.style.display = isCollapsed ? 'none' : '';
    });
  }

  function toggleMenuGroup(groupId) {
    const group = document.querySelector(`.funi-menu-group[data-group-id="${groupId}"]`);
    if (group) {
      group.classList.toggle('collapsed');
      const isCollapsed = group.classList.contains('collapsed');
      localStorage.setItem(MENU_GROUP_COLLAPSED_PREFIX + groupId, isCollapsed);

      const menuList = group.querySelector('.funi-menu-list');
      if (menuList) {
        if (isCollapsed) {
          menuList.style.height = '0px';
        } else {
          // Temporarily remove height to calculate natural height, then set it
          menuList.style.height = 'auto';
          const naturalHeight = menuList.scrollHeight + 'px';
          menuList.style.height = '0px'; // Reset to 0 for transition
          // Force reflow
          menuList.offsetHeight;
          menuList.style.height = naturalHeight;
        }
      }
    }
  }

  // Apply sidebar state on load
  document.addEventListener('DOMContentLoaded', () => {
    const sidebar = document.getElementById('sidebar');
    if (sidebar) {
      const isCollapsed = localStorage.getItem(SIDEBAR_COLLAPSED_KEY) === 'true';
      if (isCollapsed) {
        sidebar.classList.add('collapsed');
      }
      adjustMenuTextVisibility(isCollapsed);
    }

    // Apply menu group states on load and attach click listeners
    document.querySelectorAll('.funi-menu-group').forEach(group => {
      const groupId = group.dataset.groupId;
      if (groupId) {
        const isCollapsed = localStorage.getItem(MENU_GROUP_COLLAPSED_PREFIX + groupId) === 'true';
        if (isCollapsed) {
          group.classList.add('collapsed');
          const menuList = group.querySelector('.funi-menu-list');
          if (menuList) {
            menuList.style.height = '0px';
          }
        }

        const title = group.querySelector('.funi-menu-group-title');
        if (title) {
          title.addEventListener('click', () => toggleMenuGroup(groupId));
        }
      }
    });
  });

  // Expose to global scope for inline onclick
  window.toggleSidebar = toggleSidebar;
  window.toggleMenuGroup = toggleMenuGroup; // Although not directly used in HTML, good to expose if needed
})();
